package com.cxs.xiaomi.service.impl;

import com.cxs.xiaomi.dao.CartDao;
import com.cxs.xiaomi.dao.GoodsDao;
import com.cxs.xiaomi.dao.impl.CartDaoImpl;
import com.cxs.xiaomi.dao.impl.GoodsDaoImpl;
import com.cxs.xiaomi.domain.Cart;
import com.cxs.xiaomi.domain.Goods;
import com.cxs.xiaomi.service.CartService;

import java.math.BigDecimal;
import java.util.List;

/*
 * @Author:cxs
 * @Date:2021/9/15  17:03
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
public class CartServiceImpl implements CartService {

    private CartDao cartDao = new CartDaoImpl();

    private GoodsDao goodsDao = new GoodsDaoImpl();

    @Override
    public boolean addCart(Integer userId,Cart cart) {
        Goods goods = goodsDao.selectById(cart.getPid());
        if(goods != null){
            BigDecimal singlePrice = goods.getPrice();
            BigDecimal countPrice = singlePrice.multiply(new BigDecimal(cart.getNum()));
            cart.setMoney(countPrice);
            Cart cartShop = cartDao.selectByUnionPrimary(userId,goods.getId());
            if(cartShop != null){
                cartShop.setNum(cartShop.getNum() + cart.getNum());
                cartShop.setMoney(cart.getMoney().multiply(new BigDecimal(cartShop.getNum().toString())));
                return cartDao.updateByUnionPrimary(cartShop) > 0;
            }
            return cartDao.insert(cart) > 0;
        }
        return false;
    }

    @Override
    public List<Cart> getCart(Integer id) {
        List<Cart> cartList = cartDao.selectById(id);
        GoodsDao goodsDao = new GoodsDaoImpl();
        cartList.forEach(obj->{
            obj.setGoods(goodsDao.selectById(obj.getPid()));
        });
        return cartList;
    }

    @Override
    public boolean delete(Integer id, int pid) {
        return cartDao.deleteByUnionPrimary(id,pid) > 0;
    }

    @Override
    public boolean update(Integer id, int pid, int num, int money) {
        Cart cart = cartDao.selectByUnionPrimary(id, pid);
        if(cart != null){
            cart.setNum(cart.getNum() + num);
            cart.setMoney(new BigDecimal(money).multiply(new BigDecimal(cart.getNum().toString())));
            return cartDao.updateByUnionPrimary(cart) > 0;
        }
        return false;
    }

    @Override
    public boolean clearCart(Integer id) {
        return cartDao.deleteById(id) > 0;
    }
}
